package handle

import (
	"fmt"
	"io"
	"net/http"
	"os"

	"github.com/go-chi/chi/v5"
)

type Req struct {
}

func (q Req) InitRoute(party chi.Router) {
	party.Route("/req", func(r chi.Router) {
		r.Group(func(p chi.Router) {
			p.Get("/urlParam", q.URLParamDefault())
			p.Post("/form-data", q.Form())
			p.Post("/form-urlencoded", q.FormUrlencoded())
			p.Get("/query", q.ReadQuery())
			p.Post("/body", q.ReadBody())
		})
	})
}

func (q Req) URLParamDefault() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
	}
}

// However, this one will match /user/john/ and also /user/john/send
// "/user/{name}/{action:path}",
func (q Req) Form() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		err := r.ParseForm()
		if err != nil {
			panic(err)
		}
		fmt.Println(r.PostFormValue("name"))
	}
}
func (q Req) FormUrlencoded() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		err := r.ParseForm()
		if err != nil {
			panic(err)
		}
		fmt.Println(r.PostFormValue("name"))
	}
}

// ============

func (q Req) ReadQuery() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		query := r.URL.Query()
		fmt.Println(query)
	}
}
func (q Req) ReadBody() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		file, err := os.OpenFile("value.png", os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0644)
		if err != nil {
			panic(err)
		}
		wr, err := io.Copy(file, r.Body)
		if err != nil {
			panic(err)
		}
		defer r.Body.Close()
		fmt.Fprintf(w, "%v => %d bytes", r.ContentLength, wr)
	}
}
